package com.sunseagear.wind.modules.task.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunseagear.common.base.http.R;
import com.sunseagear.common.base.http.RPage;
import com.sunseagear.common.base.mvc.controller.BaseBeanController;
import com.sunseagear.common.utils.ObjectUtils;
import com.sunseagear.common.utils.StringUtils;
import com.sunseagear.wind.common.aspectj.annotation.Log;
import com.sunseagear.wind.common.aspectj.enums.LogType;
import com.sunseagear.wind.modules.task.entity.ScheduleJob;
import com.sunseagear.wind.modules.task.entity.query.ScheduleJobQuery;
import com.sunseagear.wind.modules.task.service.IScheduleJobService;
import lombok.RequiredArgsConstructor;
import org.quartz.CronExpression;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/task/schedule/job")
@Log(title = "计划任务")
@RequiredArgsConstructor
public class ScheduleJobController extends BaseBeanController {

    private final IScheduleJobService scheduleJobService;

    /**
     * 获取任务列表
     * @return 任务列表
     */
    @GetMapping(value = "list")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("task:schedule:job:list")
    public RPage<ScheduleJob> list(ScheduleJobQuery query) {
        //加入条件
        LambdaQueryWrapper<ScheduleJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ScheduleJob::getCreateDate);
        queryWrapper.like(ObjectUtils.isNotEmpty(query.getJobName()),ScheduleJob::getJobName, query.getJobName());
        // 预处理
        Page<ScheduleJob> pageBean = scheduleJobService.page(getPage(), queryWrapper);
        return RPage.success(pageBean);
    }

    /**
     *  添加任务
     * @param entity 任务实体
     * @return 操作结果
     */
    @PostMapping("add")
    @Log(logType = LogType.INSERT)
    @SaCheckPermission("task:schedule:job:add")
    public R<Void> add(@Validated @RequestBody ScheduleJob entity) {
        if (!CronExpression.isValidExpression(entity.getCronExpression())) {
            return R.fail("cron表达式格式不对");
        }
        scheduleJobService.save(entity);
        return R.success("添加成功");
    }

    /**
     * 更新任务
     * @param entity 任务实体
     * @return 操作结果
     */
    @PutMapping("update")
    @Log(logType = LogType.UPDATE)
    @SaCheckPermission("task:schedule:job:update")
    public R<Void> update(@Validated @RequestBody ScheduleJob entity) {
        if (!CronExpression.isValidExpression(entity.getCronExpression())) {
            return R.fail("cron表达式格式不对");
        }
        scheduleJobService.saveOrUpdate(entity);
        return R.success("更新成功");
    }

    /**
     * 删除任务
     * @param idList 主键集合
     * @return 操作结果
     */
    @DeleteMapping("delete")
    @Log(logType = LogType.DELETE)
    @SaCheckPermission("task:schedule:job:delete")
    public R<Void> delete(@RequestBody List<Long> idList) {
        scheduleJobService.removeBatchByIds(idList);
        return R.success("删除成功");
    }

    /**
     * 暂停或恢复任务
     * @param id 任务id
     * @param cmd 指令
     * @return 操作结果
     */
    @PostMapping(value = "{id}/changeJobStatus")
    @Log(logType = LogType.OTHER, title = "任务状态")
    @SaCheckPermission("task:schedule:job:change:job:status")
    public R<Void> changeJobStatus(@PathVariable("id") Long id, String cmd) {
        String label = "停止";
        if ("start".equals(cmd)) {
            label = "启动";
        } else {
            label = "停止";
        }
        try {
            scheduleJobService.changeStatus(id, cmd);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("任务" + label + "失败" + e.getMessage());
        }
        return R.success("任务" + label + "成功");
    }

    /**
     * 更新任务
     * @param id 任务id
     * @return 执行结果
     */
    @PostMapping(value = "{id}/updateCron")
    @Log(logType = LogType.OTHER, title = "任务更新")
    @SaCheckPermission("task:schedule:job:refresh:job")
    public R<Void> updateCron(@PathVariable("id") Long id) {
        ScheduleJob scheduleJob = scheduleJobService.getById(id);
        if (scheduleJob == null) {
            return R.fail("出错了 定时任务未找到");
        }
        if (scheduleJob.getJobStatus().equals(ScheduleJob.STATUS_DISABLE)) {
            return R.fail("该定时任务未开启");
        }
        scheduleJobService.updateCron(id);
        return R.success("任务更新成功");
    }

    /**
     * 立即执行一次任务
     * @param scheduleJob Job
     * @return 执行结果
     */
    @PostMapping(value = "/runAJobNow")
    @Log(logType = LogType.OTHER, title = "执行一次")
    @SaCheckPermission("task:schedule:job:change:job:status")
    public R<Void> runAJobNow(@RequestBody ScheduleJob scheduleJob) {
        if (scheduleJob == null) {
            return R.fail("出错了");
        }
        if (scheduleJob.getJobStatus().equals(ScheduleJob.STATUS_DISABLE)) {
            return R.fail("请开启该定时任后在执行");
        }
        scheduleJobService.runAJobNow(scheduleJob.getId());
        return R.success("任务启动成功");
    }

    /**
     * 刷新任务
     */
    @PostMapping(value = "/refreshJob")
    @Log(logType = LogType.OTHER, title = "刷新任务")
    @SaCheckPermission("task:schedule:job:refresh:job")
    public R<Void> refreshJob() {
        scheduleJobService.refreshTask();
        return R.success("刷新任务成功");
    }
}
